<template>
  <view class="search-page">
    <!-- 搜索框 -->
    <view class="search-box">
      <input 
        class="search-input" 
        v-model="keyword" 
        placeholder="输入关键字搜索" 
        placeholder-class="placeholder-style"
        @confirm="search"
      />
      <button @click="search">搜索</button>
    </view>

    <!-- 搜索历史 -->
    <view class="search-history" v-if="searchHistory.length > 0">
      <text class="history-title">搜索历史</text>
      <view 
        class="history-item" 
        v-for="(history, index) in searchHistory" 
        :key="index"
        @click="searchByHistory(history)"
      >
        <text>{{ history }}</text>
        <text class="delete-icon" @click.stop="deleteHistory(index)">×</text>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view class="search-result" v-if="searchResults.length > 0">
      <text class="result-title">搜索结果</text>
      <view 
        class="result-item" 
        v-for="(song, index) in searchResults" 
        :key="index"
        @click="playSong(song)"
      >
        <text>{{ song.name }}</text>
        <text>{{ song.ar && song.ar.length > 0 ? song.ar.map(artist => artist.name).join('/') : '未知艺术家' }}</text>
      </view>
    </view>

    <!-- 无结果提示 -->
    <view class="no-result" v-else-if="keyword && searchResults.length === 0">
      <text>没有找到相关歌曲</text>
    </view>
  </view>
</template>

<script>
import { searchSongs } from '../../common/api.js';

export default {
  data() {
    return {
      keyword: '',
      searchHistory: uni.getStorageSync('searchHistory') || [],
      searchResults: []
    };
  },
  methods: {
    // 搜索方法
    async search() {
      if (this.keyword.trim()) {
        // 添加到搜索历史
        this.addToSearchHistory(this.keyword);
        try {
          const res = await searchSongs(this.keyword);
          const validRes = res[1]?.data;
          if (!validRes || validRes.code !== 200) {
            throw new Error(validRes?.msg || '获取数据失败');
          }
          this.searchResults = validRes.result?.songs || [];
        } catch (error) {
          console.error('搜索失败:', error);
          uni.showToast({
            title: '搜索失败',
            icon: 'none'
          });
        }
      }
    },
    // 添加到搜索历史
    addToSearchHistory(keyword) {
      let history = this.searchHistory;
      // 去除重复的关键字
      history = history.filter(item => item !== keyword);
      // 添加到历史记录头部
      history.unshift(keyword);
      // 限制历史记录数量
      if (history.length > 10) {
        history.pop();
      }
      this.searchHistory = history;
      uni.setStorageSync('searchHistory', history);
    },
    // 根据历史记录搜索
    searchByHistory(keyword) {
      this.keyword = keyword;
      this.search();
    },
    // 删除历史记录
    deleteHistory(index) {
      this.searchHistory.splice(index, 1);
      uni.setStorageSync('searchHistory', this.searchHistory);
    },
    // 播放歌曲
    playSong(song) {
      const id = song.id !== undefined ? song.id : 0;
      const name = song.name || '未知歌曲';
      const artists = song.ar && song.ar.length > 0 ? song.ar.map(artist => artist.name).join('/') : '未知艺术家';
      const coverImgUrl = song.al && song.al.picUrl ? song.al.picUrl : '';
      
      uni.navigateTo({
        url: `/pages/play/play?id=${id}&name=${encodeURIComponent(name)}&artists=${encodeURIComponent(artists)}&coverImgUrl=${encodeURIComponent(coverImgUrl)}`
      });
    }
  }
};
</script>

<style scoped>
.search-page {
  padding: 20rpx;
}

.search-box {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 40rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.placeholder-style {
  color: #999;
}

.search-history {
  margin-top: 20rpx;
}

.history-title {
  font-size: 28rpx;
  color: #999;
}

.history-item {
  display: flex;
  align-items: center;
  padding: 10rpx 0;
  border-bottom: 1rpx solid #eee;
}

.delete-icon {
  color: #999;
  font-size: 32rpx;
  margin-left: 20rpx;
}

.search-result {
  margin-top: 20rpx;
}

.result-title {
  font-size: 28rpx;
  color: #999;
}

.result-item {
  display: flex;
  align-items: center;
  padding: 10rpx 0;
  border-bottom: 1rpx solid #eee;
}

.no-result {
  margin-top: 40rpx;
  text-align: center;
  color: #999;
}
</style>